package team1.project2.scribeagent;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

public class ScribeAgentThread {

	private final static ScheduledExecutorService scheduler = Executors
			.newScheduledThreadPool(1);
	static Properties properties = new Properties();

	static {
		String scribeAgentPropertiesPath = ScribeLogAgent.class
				.getResource("/").getPath()
				+ "../resources/scribeagent.properties";
		System.out.println("scribeAgentPropertiesPath:"
				+ scribeAgentPropertiesPath);
		if (scribeAgentPropertiesPath != null) {
			try {
				properties.load(new FileInputStream(new File(
						scribeAgentPropertiesPath)));
			} catch (FileNotFoundException e) {
				System.out
						.println("Unable to load file, please check properties file path, scribeAgentPropertiesPath="
								+ scribeAgentPropertiesPath);
				e.printStackTrace();
			} catch (IOException e) {
				System.out
						.println("Unable to load file, file is corrupt, please check properties file, scribeAgentPropertiesPath="
								+ scribeAgentPropertiesPath);
				e.printStackTrace();
			}
			System.out.println(properties);

		}

	}

	public static void main(String[] args) throws Exception {
		// long pollingPeriod = 10000;
		startPolling(new Long(""
				+ properties.get(ScribeAgentPropertiesKeys.POLLING_PERIOD))
				.longValue());
	}

	public static void startPolling(long pollingPeriod) throws Exception {
		System.out.println("Start Polling1");
		pollLogs(10000);
	}

	public static void pollLogs(long pollingPeriod) {
		final ScribeLogAgent scribeLogAgent = new ScribeLogAgent();

		final Runnable watcher = new Runnable() {
			public void run() {
				System.out.println("Polling database...");
				try {
					scribeLogAgent.sendVmKernelLogsDir();
					// scribeLogAgent.sendSysLogsDir();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};

		final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
				watcher, 0, pollingPeriod, MILLISECONDS);
	}
}
